﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EventBus;
using WorkFlowCore.Authorization;
using WorkFlowCore.Common.EventBus;
using WorkFlowCore.EventData;
using WorkFlowCore.Plugins;
using WorkFlowCore.WorkTasks;

namespace WorkFlowCore.Framework.EventHandlers
{
    public class TaskStateChangeEventEventHandler : ILocalEventHandler<TaskStateChangeEventData>, ITransientDependency
    {
        private readonly PluginManager pluginManager;
        private readonly IWorkflowSession session;

        public TaskStateChangeEventEventHandler()
        {
        }

        public TaskStateChangeEventEventHandler(PluginManager pluginManager, IWorkflowSession session)
        {
            this.pluginManager = pluginManager;
            this.session = session;
        }

        public async Task HandleEventAsync(TaskStateChangeEventData eventData)
        {
            session.SetUser(eventData.Session.User);
            var handlers = pluginManager.ResolveAll<ICustomTaskStateChangeEventEventHandler>();
            if(handlers != null)
            {
                foreach (var handler in handlers)
                {
                    try
                    {
                        if (handler == null) continue;
                        await handler.HandleEventAsync(eventData);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
            await Task.CompletedTask;
        }
    }
}
